package other;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ccc.test.weibo.HotItem;
import com.ccc.test.weibo.PlatformType;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author superC
 * @version 3.0.0
 * @date 2025/11/4
 */
public class WeiboUtil {

    private static final String REALTIME_URL = "https://weibo.com/ajax/side/hotSearch";

    /**
     * 从API获取热搜（更稳定）
     */
    public static List<HotItem> getHotSearchFromAPI() {
        List<HotItem> items = new ArrayList<>();

        try {
            HttpRequest request = HttpUtil.createGet(REALTIME_URL)
                    .header("User-Agent", getRandomUserAgent())
                    .header("Referer", "https://weibo.com/")
                    .header("Accept", "application/json")
                    .header("Cookie", "SUB=_2A25IUXXXDeRhGeNK6lAZ-CvKyz-IHXVqkPXbrDV6PUJbktAGLUXlkW1NQTyok5Q7wUG5S5B-2o_71K4W4S5sxRgU;")
                    .timeout(10000);

            HttpResponse response = request.execute();

            if (response.isOk()) {
                String json = response.body();
                System.out.println("原始JSON响应: " + json.substring(0, Math.min(500, json.length())) + "...");
                items = parseApiData(json);
            } else {
                System.err.println("请求失败，状态码: " + response.getStatus());
            }

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (Exception e) {
            System.err.println("微博API请求失败: " + e.getMessage());
            e.printStackTrace();
        }

        return items;
    }

    private static List<HotItem> parseApiData(String json) {
        List<HotItem> items = new ArrayList<>();

        try {
            JSONObject jsonObject = JSONUtil.parseObj(json);

            // 检查响应状态
            if (jsonObject.getInt("ok", 0) != 1) {
                System.err.println("API返回状态异常: " + jsonObject.getInt("ok", 0));
                return items;
            }

            JSONObject data = jsonObject.getJSONObject("data");
            if (data == null) {
                System.err.println("data字段为空");
                return items;
            }

            // 解析实时热搜
            JSONArray realtime = data.getJSONArray("realtime");
            if (realtime == null) {
                System.err.println("realtime字段为空");
                return items;
            }

            System.out.println("找到 " + realtime.size() + " 条热搜数据");

            for (int i = 0; i < realtime.size(); i++) {
                try {
                    JSONObject item = realtime.getJSONObject(i);

                    // 获取必要字段，提供默认值
                    String rank = String.valueOf(i + 1);
                    String title = item.getStr("word");
                    String hotValue = item.getStr("num", "0");
                    String tag = item.getStr("label_name", "");
                    String note = item.getStr("note", "");

                    // 跳过空标题的项
                    if (StrUtil.isBlank(title)) {
                        continue;
                    }

                    // 检查是否是广告
                    boolean isAd = item.getBool("is_ad", false) ||
                            "商".equals(item.getStr("small_icon_desc")) ||
                            "荐".equals(tag);

                    HotItem hotItem = HotItem.create(PlatformType.WEIBO, rank, title, hotValue);
                    hotItem.setTag(tag);
                    hotItem.setDescription(note);
                    hotItem.setAd(isAd);
                    hotItem.setTagColor(getTagColor(tag));

                    // 设置URL（如果有的话）
                    String wordScheme = item.getStr("word_scheme", "");
                    if (StrUtil.isNotBlank(wordScheme) && wordScheme.contains("#")) {
                        String topic = wordScheme.replace("#", "").trim();
                        hotItem.setUrl("https://s.weibo.com/weibo?q=" + java.net.URLEncoder.encode(topic, "UTF-8"));
                    } else {
                        hotItem.setUrl("https://s.weibo.com/weibo?q=" + java.net.URLEncoder.encode(title, "UTF-8"));
                    }

                    items.add(hotItem);

                    System.out.println("解析成功: 排名=" + rank + ", 标题=" + title + ", 热度=" + hotValue + ", 标签=" + tag);

                } catch (Exception e) {
                    System.err.println("解析第 " + (i + 1) + " 条热搜失败: " + e.getMessage());
                    // 继续解析其他项
                }
            }

        } catch (Exception e) {
            System.err.println("解析微博API数据失败: " + e.getMessage());
            e.printStackTrace();
        }

        return items;
    }

    private static String getTagColor(String tag) {
        switch (tag) {
            case "爆": return "#ff3852";
            case "热": return "#ff9600";
            case "新": return "#00b4ff";
            case "沸": return "#ff3852";
            case "荐": return "#999999";
            case "商": return "#00b7ee";
            default: return "#cccccc";
        }
    }

    private static String getRandomUserAgent() {
        List<String> userAgents = CollUtil.newArrayList(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
                "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
        );
        return RandomUtil.randomEle(userAgents);
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        System.out.println("开始获取微博热搜...");
        List<HotItem> hotItems = getHotSearchFromAPI();

        System.out.println("\n=== 微博热搜榜 ===");
        System.out.println("共获取到 " + hotItems.size() + " 条热搜");

        for (HotItem item : hotItems) {
            String adMark = item.isAd() ? "[广告] " : "";
            System.out.printf("排名：%2s | %s标题：%-30s | 热度：%8s | 标签：%s%n",
                    item.getRank(), adMark, item.getTitle(),
                    item.getHotValue(), item.getTag());
        }
    }

}
